package org.piggy.server.rpc.handler;

import com.alibaba.fastjson2.JSONObject;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.piggy.common.async.RequestFuture;
import org.piggy.common.async.Response;
import org.piggy.server.rpc.core.Mediator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(ServerHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        logger.info("client request body==========="+msg.toString());
        RequestFuture request = JSONObject.parseObject(msg.toString(), RequestFuture.class);
        Response response = Mediator.process(request);
        String body = JSONObject.toJSONString(response);
        logger.info("serve response body==========="+body);
        ctx.channel().writeAndFlush(body);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        logger.error("connect close");
        ctx.close();
    }
}
